package cn.iocoder.yudao.module.infra.controller.admin.codegen;

import cn.iocoder.yudao.module.infra.service.codegen.DynamicComponentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/magic-cmp")
public class DynamicComponentController {

    @Resource
    private DynamicComponentService dynamicComponentService;

    public DynamicComponentController(){
        log.info(" =========> DynamicComponentController init ==========> ");
    }

    // 返回 JS 文件
    @GetMapping("/script/{name}")
    public ResponseEntity<ByteArrayResource> getJsFileById(@PathVariable String name) {
        String compileJs = dynamicComponentService.selectJsByName(name);
        if (StringUtils.isBlank(compileJs)) {
            return ResponseEntity.notFound().build();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/javascript"));
        headers.setContentDisposition(ContentDisposition.builder("inline")
                .filename(name + ".js")  // 使用组件名称作为文件名
                .build());

        byte[] jsBytes = compileJs.getBytes(StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .headers(headers)
                .body(new ByteArrayResource(jsBytes));
    }

    // 返回 CSS 文件
    @GetMapping("/style/{name}")
    public ResponseEntity<ByteArrayResource> getCssFileById(@PathVariable String name) {
        String compileCss = dynamicComponentService.selectCssByName(name);
        if (StringUtils.isBlank(compileCss)) {
            return ResponseEntity.notFound().build();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("text/css"));
        headers.setContentDisposition(ContentDisposition.builder("inline")
                .filename(name + ".css")
                .build());

        byte[] cssBytes = compileCss.getBytes(StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .headers(headers)
                .body(new ByteArrayResource(cssBytes));
    }
}